
package chatclient;

import chatqueue.ChatQueuePackage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;


public class MessageService implements MessageListener {
    @Resource(mappedName = "jms/chatQueue")
    private static Topic chatQueue;
    @Resource(mappedName = "jms/chatQueueFactory")
    private static ConnectionFactory chatQueueFactory;

    public Destination clientDestination = null;

    private GUI gui;

    public MessageService() {
        gui = new GUI(this);

    }

    public static void main(String[] args) {
        MessageService messageService = new MessageService();

        try {
            messageService.startTopicListener();
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void getNextInQueue() {
        ChatQueuePackage cqp = new ChatQueuePackage();
        try {
            this.sendJMSMessageToChatQueue(cqp);
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void queueUp() {
        ChatQueuePackage cqp = new ChatQueuePackage(true, null);
        try {
            this.sendJMSMessageToChatQueue(cqp);
        } catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void onMessage(Message message) {
        try {
            gui.newMessage(message);

            System.out.println("success!!!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(Destination destination, String text) {
        try {
            sendJMSMessage(destination, new ChatQueuePackage(false, text));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Message createJMSMessage(Session session, ChatQueuePackage messageData) throws JMSException {
        // TODO create and populate message to send
        ObjectMessage tm = session.createObjectMessage();
        //System.out.println(clientDestination);
        tm.setJMSReplyTo(clientDestination);
        tm.setObject(messageData);
        return tm;
    }

    private void sendJMSMessageToChatQueue(ChatQueuePackage messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = chatQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(chatQueue);
            messageProducer.send(createJMSMessage(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    private void sendJMSMessage(Destination destination, ChatQueuePackage messageData) throws Exception {
        Connection connection = null;
        Session session = null;
        try {
            connection = chatQueueFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //Destination clientDestination = (Destination) initContext.lookup(destination);
            MessageProducer messageProducer = session.createProducer(destination);
            messageProducer.send(createJMSMessage(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

    public void startTopicListener() throws JMSException {

        /*InitialContext initContext = new InitialContext();
        ConnectionFactory factory =
            (ConnectionFactory) initContext.lookup("jms/chatQueueFactory");
        initContext.close();*/
        //chatQueueFactory.createConnection();
        Connection connection = chatQueueFactory.createConnection();
        Session session =
            connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        this.clientDestination = session.createTemporaryTopic();
        MessageConsumer receiver = session.createConsumer(this.clientDestination);
        receiver.setMessageListener(this);
        connection.start();
    }
}
